package com.joe.demo.chat.client;

import com.joe.demo.chat.message.*;
import com.joe.demo.chat.protocol.MessageCodecSharable;
import com.joe.demo.chat.protocol.ProtocolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;


/**
 * @Description
 * @Author gaojw
 * @Date 2024-08-30
 */
@Slf4j
public class ChatClient {

    public static void main(String[] args) {
        final NioEventLoopGroup group = new NioEventLoopGroup();
        final LoggingHandler loggingHandler = new LoggingHandler(LogLevel.INFO);
        final MessageCodecSharable messageCodecSharable = new MessageCodecSharable();
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        final AtomicBoolean LOGIN = new AtomicBoolean(false);

        try {
            final Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
            bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel channel) throws Exception {
                    channel.pipeline().addLast(new ProtocolFrameDecoder());
                    channel.pipeline().addLast(loggingHandler);
                    channel.pipeline().addLast(messageCodecSharable);

                    // 用来判断，读空闲时间、写空闲时间是不是过长
                    // 3s 内没有向写 channel 的数据，会触发一个事件 IdleState#WRITE_IDLE 事件
                    channel.pipeline().addLast(new IdleStateHandler(0, 3, 0));
                    // ChannelDuplexHandler 可同时作为出站和入站事件
                    channel.pipeline().addLast(new ChannelDuplexHandler(){
                        /**
                         * 用来触发特殊事件
                         * @param ctx
                         * @param evt
                         * @throws Exception
                         */
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            final IdleStateEvent event = (IdleStateEvent) evt;
                            // 触发读空闲事件
                            if (event.state() == IdleState.WRITER_IDLE){
//                                log.info("已经 3s 没有写数据了，发送一个心跳包");
                                ctx.channel().writeAndFlush(new PingMessage());
                            }
                        }
                    });


                    channel.pipeline().addLast("client handler", new ChannelInboundHandlerAdapter(){
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            // 连接建立后会触发的事件
                            new Thread(()->{
                                // 负责接收用户在控制台的输入，负责向服务器发送消息
                                final Scanner scanner = new Scanner(System.in);
                                System.out.println("请输入用户名：");
                                final String username = scanner.nextLine();
                                System.out.println("请输入密码：");
                                final String password = scanner.nextLine();
                                // 构建消息
                                final LoginRequestMessage loginRequestMessage = new LoginRequestMessage(username, password, null);
                                // 发送消息
                                ctx.writeAndFlush(loginRequestMessage);

                                System.out.println("等待后续操作");
                                try {
                                    WAIT_FOR_LOGIN.await();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                                if (!LOGIN.get()){
                                    ctx.channel().close();
                                    return;
                                }

                                while (true){
                                    System.out.println("====================================");
                                    System.out.println("send [username] [content]");
                                    System.out.println("gsend [group name] [content]");
                                    System.out.println("gcreate [group name] [m1,m2,m3...]");
                                    System.out.println("gmember [group name]");
                                    System.out.println("gjoin [group name]");
                                    System.out.println("gquit [group name]");
                                    System.out.println("quit");
                                    System.out.println("====================================");
                                    final String command = scanner.nextLine();
                                    final String[] array = command.split(" ");
                                    switch (array[0]){
                                        case "send":
                                            ctx.writeAndFlush(new ChatRequestMessage(username, array[1], array[2]));
                                            break;
                                        case "gsend":
                                            ctx.writeAndFlush(new GroupChatRequestMessage(username, array[1], array[2]));
                                            break;
                                        case "gcreate":
                                            final HashSet<String> set = new HashSet<>(Arrays.asList(array[2].split(",")));
                                            // 加入自己
                                            set.add(username);
                                            ctx.writeAndFlush(new GroupCreateRequestMessage(array[1], set));
                                            break;
                                        case "gmember":
                                            ctx.writeAndFlush(new GroupMembersRequestMessage(array[1]));
                                            break;
                                        case "gjoin":
                                            ctx.writeAndFlush(new GroupJoinRequestMessage(username, array[1]));
                                            break;
                                        case "gquit":
                                            ctx.writeAndFlush(new GroupQuitRequestMessage(username, array[1]));
                                            break;
                                        case "quit":
                                            ctx.channel().close();
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            }, "system in").start();
                            super.channelActive(ctx);
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            log.info("msg: {}", msg);
                            if (msg instanceof LoginResponseMessage){
                                final LoginResponseMessage responseMessage = (LoginResponseMessage) msg;
                                if (responseMessage.isSuccess()) {
                                    // 登录成功
                                    LOGIN.set(true);
                                }
                                // 唤醒登录线程
                                WAIT_FOR_LOGIN.countDown();
                            }
                            super.channelRead(ctx, msg);
                        }

                        /**
                         * 连接断开时，触发
                         * @param ctx
                         * @throws Exception
                         */
                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            log.debug("连接已经断开，按任意键退出..");
                            super.channelInactive(ctx);
                        }

                        /**
                         * 在出现异常时触发
                         * @param ctx
                         * @param cause
                         * @throws Exception
                         */
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            log.debug("连接已经断开，按任意键退出..{}", cause.getMessage());
                            super.exceptionCaught(ctx, cause);
                        }
                    });
                }
            });
            final Channel channel = bootstrap.connect(new InetSocketAddress("localhost", 8080)).sync().channel();
            channel.closeFuture().sync();
        }catch (InterruptedException exception){
            exception.printStackTrace();
            log.error("客户端异常：", exception);
        }finally {
            group.shutdownGracefully();
        }
    }
}
